﻿using System;

namespace Gamelight.Graphics
{
	public enum ImageScaleMode
	{
		Interpolate,
		NearestNeighbor
	}

	public static class Transformation
	{
		public static Image Scale(Image originalImage, int newWidth, int newHeight, ImageScaleMode scaleMode)
		{
			Image output = new Image(newWidth, newHeight);
			switch (scaleMode)
			{
				case ImageScaleMode.Interpolate:
					throw new NotImplementedException("Scale interpolate is not implemented");
					//ScaleInterpolate(originalImage, output);
					//break;

				case ImageScaleMode.NearestNeighbor:
					ScaleNearestNeighbor(originalImage, output);
					break;
			}
			
			return output;
		}

		public static Image FlipHorizontally(Image originalImage)
		{
			Image output = new Image(originalImage);

			int width = originalImage.Width;
			int height = originalImage.Height;
			int value;
			int[] pixels = output.Pixels;

			for (int y = 0; y < height; ++y)
			{
				for (int x = 0; x < width / 2; ++x)
				{
					value = pixels[x + y * width];
					pixels[x + y * width] = pixels[(width - x - 1) + y * width];
					pixels[(width - x - 1) + y * width] = value;
				}
			}

			return output;
		}

		public static Image FlipVertically(Image originalImage)
		{
			Image output = new Image(originalImage);

			int width = originalImage.Width;
			int height = originalImage.Height;
			int value;
			int[] pixels = output.Pixels;

			for (int x = 0; x < width; ++x)
			{
				for (int y = 0; y < height / 2; ++y)
				{
					value = pixels[x + y * width];
					pixels[x + y * width] = pixels[x + (height - y - 1) * width];
					pixels[x + (height - y - 1) * width] = value;
				}
			}

			return output;
		}

		/* 
		//TODO: make this work in non UI thread
		private static void ScaleInterpolate(Image source, Image target)
		{
			System.Windows.Controls.Image swcImage = new System.Windows.Controls.Image() { Source = source._Bmp, Width = target.Width, Height = target.Height };
			System.Windows.Media.Imaging.WriteableBitmap wbmp = new System.Windows.Media.Imaging.WriteableBitmap(swcImage, null);
			target._Bmp = wbmp;
		}
		*/

		private static void ScaleNearestNeighbor(Image source, Image target)
		{
			int x, y;
			int width = target.Width;
			int height = target.Height;
			int sourceWidth = source.Width;
			int sourceHeight = source.Height;

			int[] targetPixels = target.Pixels;
			int[] sourcePixels = source.Pixels;

			for (y = 0; y < height; ++y)
			{
				for (x = 0; x < width; ++x)
				{
					/*
					// This is what the expanded code actually does...
					targetX = x * sourceWidth / width;
					targetY = y * sourceHeight / height;
					value = source.Bmp.Pixels[targetX + targetY * width];
					targetPixels[x + width * y] = value;
					*/
					targetPixels[x + width * y] = sourcePixels[(x * sourceWidth / width) + (y * sourceHeight / height) * sourceWidth];
				}
			}
		}
	}
}
